#!/usr/bin/env python
# coding=utf-8


try:
    from cStringIO import StringIO
except ImportError:
    try:
        from StringIO import StringIO
    except ImportError:
        from io import StringIO
import logging
import base64
from flask import Blueprint, request, session, g, redirect, url_for, make_response, abort
from flask_login import login_required
import qrcode

from over.model import db, ShadowsocksAccount
from over.handlers.helper import json_dumps, json_loads, random_str, jsonify

logger = logging.getLogger("over.qr")
mod = Blueprint(__name__, 'qr')


@mod.route('/')
@login_required
def index():
    account = request.args.get('account')
    account = ShadowsocksAccount.query.get_or_404(account)

    if account.user_id != g.user.id:
        return abort(404)

    value = '%s:%s@%s:%s' % (account.encryption_type, account.password, account.ip, account.port)
    value = 'ss://' + base64.b64encode(value)
    code = qrcode.make(value, box_size=3)

    buff = StringIO()
    code.save(buff, "jpeg")

    response = make_response(buff.getvalue())
    response.headers['Content-Type'] = 'image/jpeg'
    return response
